from app.models.user import User
from app.extensions import db
from flask_jwt_extended import create_access_token
from werkzeug.exceptions import Unauthorized

def register_user(username, password):
    """ 服务层：注册业务逻辑 """
    # 1. 检查用户名是否存在
    if User.query.filter_by(username=username).first():
        raise ValueError("用户名已存在")  # 抛出业务异常
    # 2. 创建用户
    user = User(username=username)
    user.set_password(password)  # 密码加密
    # 3. 保存到数据库
    db.session.add(user)
    db.session.commit()

    return user  # 返回用户对象

class AuthService:
    """ 服务层：登录业务类 """
    @staticmethod
    def authenticate(username, password):
        """
        认证逻辑核心方法
        返回: (access_token, user) 或 抛出异常
        """
        # 1. 查找用户
        user = User.query.filter_by(username=username).first()
        if not user:
            raise Unauthorized("用户不存在")

        # 2. 验证密码
        if not user.check_password(password):
            raise Unauthorized("密码错误")

        # 3. 生成令牌
        return create_access_token(identity=user.id), user

    @staticmethod
    def validate_login_data(data):
        """验证登录数据格式"""
        if not data or 'username' not in data or 'password' not in data:
            raise ValueError("需要用户名和密码字段")
